#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System.IO;
using Neatly.Helper;
using Pandora;
using PandoraEditor;
using UnityEditor;
using UnityEngine;

namespace NeatlyEditor
{
    public static class LuaBuilder
    {
        private static void ClearLuaDirectory()
        {
            PdrFileUtil.DeleteDirectory(NeatlyEditorConfig.PATH_TEMP_LUA32);
            PdrFileUtil.DeleteDirectory(NeatlyEditorConfig.PATH_TEMP_LUA64);
        }

        public static void BuildSource()
        {
            ClearLuaDirectory();
#if UNITY_WEBGL
            string suffix = ".bytes";
#else
            string suffix = "";
#endif
            CreateLuaSource(NeatlyEditorConfig.PATH_TOLUA, NeatlyEditorConfig.PATH_TEMP_LUA32, suffix);
            CreateLuaSource(NeatlyEditorConfig.PATH_LUA, NeatlyEditorConfig.PATH_TEMP_LUA32, suffix);
            CreateLuaSource(NeatlyEditorConfig.PATH_TOLUA, NeatlyEditorConfig.PATH_TEMP_LUA64, suffix);
            CreateLuaSource(NeatlyEditorConfig.PATH_LUA, NeatlyEditorConfig.PATH_TEMP_LUA64, suffix);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        private static void CreateLuaSource(string inputPath, string outputPath, string suffix = "")
        {
            inputPath = inputPath.ToLower().Replace('\\', '/') + "/";
            var filePathList = PdrFileUtil.GetFilesName(inputPath, ".lua");
            foreach (var filePath in filePathList)
            {
                var content = File.ReadAllText(filePath);
                var outputFileName = filePath.Replace('\\', '/').Replace(inputPath, "").Replace(".lua", suffix).Replace("/", "_");
                var outputFilePath = Path.Combine(outputPath, outputFileName).ToLower();
                PdrFileUtil.CreateDirectoryFromFile(outputFilePath);
                File.WriteAllText(outputFilePath, AesEncryptUtility.Encrypt(content));
            }
        }

        public static void Build()
        {
#if UNITY_WEBGL
            BuildSource();
#else
            ClearLuaDirectory();
            BuildLua($"{NeatlyEditorConfig.PATH_LUA},{NeatlyEditorConfig.PATH_TOLUA}", NeatlyEditorConfig.PATH_TEMP);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
#endif
        }

        private static void BuildLua(string inputPath, string outputPath)
        {
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            var builder = PdrCombine.ProjectRoot(UserSetting.CompileSetting.lua_builder);
#if UNITY_WEBGL
            string suffix = ".bytes";
#else
            string suffix = "";
#endif
            string args = $"{builder} {inputPath} {outputPath} {suffix}";
            Debug.Log(args);
            PdrCMDHelper.ProcessPython(args);
        }
    }
}